package com.findviewbydream.evil.eda.Welcome;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.InterpolatorRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.findviewbydream.evil.eda.Data.Data;
import com.findviewbydream.evil.eda.Data.IntentData;
import com.findviewbydream.evil.eda.Data.UserData;
import com.findviewbydream.evil.eda.Login.Login;
import com.findviewbydream.evil.eda.MainActivity;
import com.findviewbydream.evil.eda.MainActivity_Include_Patch;
import com.findviewbydream.evil.eda.R;
import com.findviewbydream.evil.eda.Utils.Encryp_AES;
import com.findviewbydream.evil.eda.Utils.NetUtils;
import com.findviewbydream.evil.eda.Utils.SAcp;
import com.findviewbydream.evil.eda.Utils.Utils;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

/********************************************
 * 工程名：Eda
 * 包名：com.findviewbydream.evil.eda.Welcome
 * 时间：16-7-8 上午9:16
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：欢迎界面
 ********************************************/
public class Welcome extends AppCompatActivity
{
    private ImageView welcome_img;

    private String downloadURL;
    private ImageView welcome_bottom_1;
    private ImageView welcome_bottom_2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome);

        initView();
        startAnimation();/*开始动画*/
        //isNetworkConnected();/*先判断网络是否链接,然后检查更新*/
        getIMEIPermissions();/*先获取IMEI，然后再isNetworkConnected*/
    }

    /**
     * 初始化控件
     */
    private void initView()
    {
        welcome_img = (ImageView) findViewById(R.id.welcome_img);
        welcome_bottom_1 = (ImageView) findViewById(R.id.welcome_bottom_1);
        welcome_bottom_2 = (ImageView) findViewById(R.id.welcome_bottom_2);
    }


    /**
     * 启动的动画
     */
    private void startAnimation()
    {
        new Utils.SHandler()
        {
            @Override
            public void handler()
            {
                Utils.Glide(R.drawable.welcome_loading, welcome_img);
                Animation topAnim = new AlphaAnimation(0, 1);
                topAnim.setDuration(2000);
                welcome_img.startAnimation(topAnim);


                Glide.with(Welcome.this).load(R.drawable.welcome_bottom_1).into(welcome_bottom_1);
                Animation bottomAnim_1 = new TranslateAnimation(-500, 0, 0, 0);
                bottomAnim_1.setDuration(2000);
                bottomAnim_1.setInterpolator(new BounceInterpolator());
                welcome_bottom_1.startAnimation(bottomAnim_1);

                Glide.with(Welcome.this).load(R.drawable.welcome_bottom_2).into(welcome_bottom_2);
                Animation bottomAnim_2 = new TranslateAnimation(500, 0, 0, 0);
                bottomAnim_2.setDuration(2000);
                bottomAnim_2.setInterpolator(new BounceInterpolator());
                welcome_bottom_2.startAnimation(bottomAnim_2);
            }
        }.start(300);
    }

    /**
     * 读取用户信息
     * 判断登陆信息，如果信息正确，直接登陆
     */
    private void readUserInformation()
    {
        final SharedPreferences sharedPreferences = getSharedPreferences("user", MODE_PRIVATE);
        final String imei = sharedPreferences.getString("ui", "");
        final String phone = sharedPreferences.getString("up", "");
        new SAcp()
        {
            @Override
            public void onGranteds()
            {
                if (imei.equals(Utils.getIMEI()))
                {
                    /*如果验证正确，则进行网络验证，正确登陆*/
                    if (!phone.equals("") && !imei.equals(""))
                        toLoginNetWork(phone, imei);
                    /*如果验证失败或为空，跳转到登陆界面*/
                    else
                    {
                        startActivity(new Intent(Welcome.this, Login.class));
                        finish();
                    }
                }
                else
                {
                    startActivity(new Intent(Welcome.this, Login.class));
                    finish();
                }
            }

            @Override
            public void onDenieds()
            {
                SAcp.showDialog(Welcome.this, Welcome.this);
            }
        }.getPermissions(Manifest.permission.READ_PHONE_STATE);
    }

    /**
     * 检测登陆信息，如果正确，直接登陆
     */
    private void toLoginNetWork(final String phone, String imei)
    {
        OkHttpUtils.post().url(Data.IP + "LoginServlet")
                .addParams("type", "login")
                .addParams("phone", phone)
                .addParams("imei", imei)
                .build()
                .execute(new StringCallback()
                {
                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                        startActivity(new Intent(Welcome.this, Login.class));
                        finish();
                    }

                    @Override
                    public void onResponse(String response, int id)
                    {
                        Utils.Logger(response);
                        /*todo：以后会有引导页判断引导页*/
                        if (response.equals("SUCCESS"))
                        {
                            UserData.setUserPhoneNum(phone);
                            // startActivity(new Intent(Welcome.this, MainActivity.class));
                            startActivity(new Intent(Welcome.this, IntentData.getMainActivity()));
                            finish();
                        }
                        else
                        {
                            startActivity(new Intent(Welcome.this, Login.class));
                            finish();
                        }
                    }
                });
    }


    /**
     * 判断网络是否连接
     */
    private void isNetworkConnected()
    {
        if (Utils.getNetworkType() == 0)
        {
            final MaterialDialog dialog = new MaterialDialog(this);
            dialog.content("亲,您确认联网了吗?")
                    .isTitleShow(false)
                    .btnNum(3)
                    .btnText("检查", "重试", "打开wifi")
                    .show();

            dialog.setOnBtnClickL(
                    () -> startActivity(new
                            Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS))
                    , () -> {
                        dialog.dismiss();
                        isNetworkConnected();
                    }
                    , () -> {
                        WifiManager wm = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
                        wm.setWifiEnabled(true);
                    }
            );
        }
        else
            toNetWork();
    }

    /**
     * 网络加载
     */
    private void toNetWork()
    {
        OkHttpUtils.get().url(Data.IP + "Version")
                .addParams("type", "update")
                .addParams("versionCode", Utils.getVersionCode() + "")
                .build()
                .execute(new StringCallback()
                {
                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                        Utils.Log(e.toString());
                        NetUtils.reportError(Welcome.this, e);
                    }

                    @Override
                    public void onResponse(final String response, int id)
                    {
                        if (response.equals("false"))
                        {
                            new Utils.SHandler()
                            {
                                @Override
                                public void handler()
                                {
                                    /*startActivity(new Intent(Welcome.this, MainActivity.class));
                                    finish();*/
                                    readUserInformation();
                                }
                            }.start(2500);
                        }
                        else
                        {
                            final MaterialDialog dialog = new MaterialDialog(Welcome.this);
                            dialog.setCancelable(false);
                            dialog.setCanceledOnTouchOutside(false);
                            dialog.content("检查到更新,是否开始下载?")
                                    .title("更新提示")
                                    .btnNum(1)
                                    .btnText("确定")
                                    .show();
                            dialog.setOnBtnClickL(new OnBtnClickL()
                            {
                                @Override
                                public void onBtnClick()
                                {
                                    downloadURL = response;
                                    checkNet();
                                }
                            });
                        }
                    }
                });
    }

    /**
     * 检测是否有网络,是否为流量
     */
    private void checkNet()
    {
        int netType = Utils.getNetworkType();

        if (netType == 0)
        {
            final MaterialDialog dialog = new MaterialDialog(this);
            dialog.content("亲,您确认联网了吗?")
                    .isTitleShow(false)
                    .btnNum(2)
                    .btnText("重试", "检查")
                    .show();

            dialog.setOnBtnClickL(new OnBtnClickL()
            {
                @Override
                public void onBtnClick()
                {
                    dialog.dismiss();
                    isNetworkConnected();
                }
            }, new OnBtnClickL()
            {
                @Override
                public void onBtnClick()
                {
                    startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                }
            });
        }
        else if (netType == Utils.NETTYPE_CMNET || netType == Utils.NETTYPE_CMWAP)
        {
            final MaterialDialog dialog = new MaterialDialog(this);
            dialog.content("亲,您正在使用流量哦,确认下载?")
                    .isTitleShow(false)
                    .btnNum(2)
                    .btnText("取消", "确定")
                    .show();
            dialog.setOnBtnClickL(new OnBtnClickL()
            {
                @Override
                public void onBtnClick()
                {
                    dialog.dismiss();
                }
            }, new OnBtnClickL()
            {
                @Override
                public void onBtnClick()
                {
                    getPermissions();/*先获取权限,然后下载*/
                }
            });
        }
        else
        {
            getPermissions();/*先获取权限,然后下载*/
        }

    }

    /*zhibanshi1234*/

    /**
     * 获取权限
     * <p/>
     * 权限获取失败即退出
     */
    private void getPermissions()
    {
        new SAcp()
        {
            @Override
            public void onGranteds()
            {
                startActivity(new Intent(Welcome.this
                        , UpdateDownload.class)
                        .putExtra("downloadURL", downloadURL));
                finish();
            }

            @Override
            public void onDenieds()
            {
                SAcp.showDialog(Welcome.this, Welcome.this);
            }
        }.getPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }


    private void getIMEIPermissions()
    {
        new SAcp()
        {
            @Override
            public void onGranteds()
            {
                UserData.setUserIMEI(Utils.getIMEI());
                isNetworkConnected();
            }

            @Override
            public void onDenieds()
            {
                SAcp.showDialog(Welcome.this, Welcome.this);
            }
        }.getPermissions(Manifest.permission.READ_PHONE_STATE);
    }


}
